<template>
    <view>
        <!-- pages/deviceList/deviceList.wxml -->
        <view class="tabs">
            <view class="item">
                <van-dropdown-menu :active-color="mainColor">
                    <van-dropdown-item :value="storeId" :options="stores" @change="storeDropdown" />
                    <van-dropdown-item :value="deviceType" :options="deviceTypes" @change="typeDropdown" />
                </van-dropdown-menu>
            </view>
        </view>

        <view class="container">
            <view class="list">
                <view :class="'item ' + (item.status == 1 ? 'online' : 'offline')" v-for="(item, index) in deviceList" :key="index">
                    <view class="line1">
                        <view class="info">
                            <label>编号：</label>
                            <text class="sn">{{ item.deviceSn }}</text>
                        </view>
                        <view class="info">
                            <label>类型：</label>
                            <text>
                                {{
                                    item.type == 1
                                        ? '门禁'
                                        : item.type == 2
                                        ? '空开'
                                        : item.type == 3
                                        ? '云喇叭'
                                        : item.type == 4
                                        ? '灯具'
                                        : item.type == 5
                                        ? '密码锁'
                                        : item.type == 6
                                        ? '网关'
                                        : item.type == 7
                                        ? '插座'
                                        : item.type == 8
                                        ? '锁球器控制器（12V）'
                                        : item.type == 9
                                        ? '人脸门禁机'
                                        : item.type == 10
                                        ? '智能语音喇叭'
                                        : '二维码识别器'
                                }}
                            </text>
                        </view>
                        <view class="info" v-if="item.type != 6 && item.type != 5">
                            <label>状态：</label>
                            <text>{{ item.status == 1 ? '在线' : '离线' }}</text>
                        </view>
                    </view>

                    <view class="line2">
                        <view class="info" v-if="item.storeName">
                            <label>门店：</label>
                            <text class="name">{{ item.storeName }}</text>
                        </view>
                        <view class="info">
                            <block v-if="item.roomName">
                                <label>房间：</label>
                                <text>{{ item.roomName }}</text>
                            </block>
                            <block v-else>
                                <view>-</view>
                            </block>
                        </view>
                        <view class="del" @tap="delDevice" :data-id="item.deviceId">删除</view>
                    </view>
                </view>
            </view>
            <view class="buttom">- 加载完毕 -</view>
        </view>

        <!-- 底部按钮 -->
        <view :class="'bottom bg-primary ' + (isIpx ? 'fix-iphonex-button' : '')" @tap="add">添加设备</view>
        <!-- 添加弹窗 -->
        <van-dialog
            use-slot
            title="添加设备"
            :show="showAdd"
            show-cancel-button
            @confirm="submitAdd"
            @cancel="cancelAdd"
            :before-close="beforeCloseFunction"
            :confirm-button-color="mainColor"
        >
            <view class="dialog">
                <van-cell-group>
                    <van-field v-model="deviceSn" label="设备编号：" maxlength="10" placeholder="请输入,最长10位数" />
                    <van-field label="设备类型：" placeholder="请选择">
                        <picker slot="input" @change="bindDeviceTypeSelect" :value="deviceTypeIndex" range-key="text" :range="deviceTypes">
                            <view class="picker">
                                <input type="text" disabled placeholder="请选择类型" placeholder-class="plh" :value="deviceTypes[deviceTypeIndex].text" />
                                <van-icon name="arrow-down" />
                            </view>
                        </picker>
                    </van-field>
                    <van-field label="门店：" placeholder="请选择门店">
                        <picker slot="input" @change="bindStoreSelect" :value="storeIndex" range-key="text" :range="stores">
                            <view class="picker">
                                <input type="text" disabled placeholder="请选择门店" placeholder-class="plh" :value="stores[storeIndex].text" />
                                <van-icon name="arrow-down" />
                            </view>
                        </picker>
                    </van-field>
                    <van-field label="房间：" placeholder="请选择房间">
                        <picker slot="input" @change="bindRoomSelect" :value="roomIndex" range-key="text" :range="roomList">
                            <view class="picker">
                                <input type="text" disabled placeholder="请选择房间" placeholder-class="plh" :value="roomList[roomIndex].text" />
                                <van-icon name="arrow-down" />
                            </view>
                        </picker>
                    </van-field>
                    <view class="tips">注：网关、人脸识别机、前台云喇叭、门店大门门禁</view>
                    <view class="tips">等设备不需要绑定房间，只绑定门店即可</view>
                    <text style="font-size: 26rpx; margin-left: 30rpx">共用设备：</text>
                    <switch @change="changeSwitchStatus" :checked="shareDevice" />
                    <view class="tips">注:表示多个房间或台桌共用，常用于中央空调</view>
                </van-cell-group>
            </view>
        </van-dialog>
    </view>
</template>

<script>
const app = getApp();
var http = require('../../../utils/http');
export default {
    data() {
        return {
            storeId: '',
            stores: [],
            storeIndex: '',
            roomList: [],
            roomIndex: '',

            deviceTypes: [
                {
                    value: '',
                    text: '请选择类型'
                },
                {
                    value: 1,
                    text: '门禁'
                },
                {
                    value: 2,
                    text: '空开'
                },
                {
                    value: 3,
                    text: '云喇叭'
                },
                {
                    value: 4,
                    text: '灯具'
                },
                {
                    value: 5,
                    text: '密码锁'
                },
                {
                    value: 6,
                    text: '网关'
                },
                {
                    value: 7,
                    text: '插座'
                },
                {
                    value: 8,
                    text: '锁球器控制器（12V）'
                },
                {
                    value: 9,
                    text: '人脸门禁机'
                },
                {
                    value: 10,
                    text: '智能语音喇叭'
                },
                {
                    value: 11,
                    text: '二维码识别器'
                }
            ],

            deviceTypeIndex: '',
            deviceType: '',
            deviceList: [],
            isIpx: app.globalData.isIpx ? true : false,
            pageNo: 1,
            pageSize: 10,
            canLoadMore: true,
            showAdd: false,
            deviceSn: '',
            shareDevice: false,
            beforeCloseFunction: null,
            mainColor: '',
            text: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad(options) {
        this.getXiaLaListAdmin();
        this.setData({
            beforeCloseFunction: this.beforeClose()
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getDeviceList('refresh');
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        let that = this;
        that.pageNo = 1;
        this.getDeviceList('refresh');
        that.canLoadMore = true;
        uni.stopPullDownRefresh();
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        let that = this;
        if (that.canLoadMore) {
            that.pageNo++;
            this.getDeviceList('');
        } else {
            uni.showToast({
                title: '我是有底线的...'
            });
        }
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {},
    methods: {
        beforeClose() {
            // 这里一定要用箭头函数，否则访问不到this
            return (type) => {
                //console.log(type)
                if (type === 'cancel') {
                    // 点击取消
                    return true;
                } else {
                    // 点击确定
                }
            };
        },

        //管理员获取门店下拉列表数据
        getXiaLaListAdmin: function (e) {
            var that = this;
            //if (app.globalData.isLogin)
            {
                http.request(
                    '/member/store/getStoreList',
                    '1',
                    'get',
                    {},
                    app.globalData.userDatatoken.accessToken,
                    '',
                    function success(info) {
                        console.info('下拉门店数据===');
                        console.info(info);
                        if (info.code == 0) {
                            let stores = [];
                            info.data.map((it) => {
                                stores.push({
                                    text: it.key,
                                    value: it.value
                                });
                            });
                            stores.unshift({
                                text: '请选择门店',
                                value: ''
                            });
                            that.setData({
                                stores: stores
                            });
                        } else {
                            uni.showModal({
                                content: '请求服务异常，请稍后重试',
                                showCancel: false
                            });
                        }
                    },
                    function fail(info) {}
                );
            }
        },

        //管理员获取房间下拉列表数据
        getRoomListAdmin: function (storeId) {
            var that = this;
            //if (app.globalData.isLogin)
            {
                http.request(
                    '/member/store/getRoomList/' + storeId,
                    '1',
                    'get',
                    {},
                    app.globalData.userDatatoken.accessToken,
                    '',
                    function success(info) {
                        console.info('下拉房间数据===');
                        if (info.code == 0) {
                            let roomList = [];
                            info.data.map((it) => {
                                roomList.push({
                                    text: it.key,
                                    value: it.value
                                });
                            });
                            roomList.unshift({
                                text: '请选择房间',
                                value: ''
                            });
                            that.setData({
                                roomList: roomList
                            });
                        } else {
                            uni.showModal({
                                content: '请求服务异常，请稍后重试',
                                showCancel: false
                            });
                        }
                    },
                    function fail(info) {}
                );
            }
        },

        // 获取设备列表
        getDeviceList: function (e) {
            let that = this;
            if (app.globalData.isLogin) {
                if (e == 'refresh') {
                    //刷新，page变为1
                    that.setData({
                        deviceList: [],
                        pageNo: 1,
                        canLoadMore: true
                    });
                }
                http.request(
                    '/member/device/getDevicePage',
                    '1',
                    'post',
                    {
                        pageNo: that.pageNo,
                        pageSize: that.pageSize,
                        type: that.deviceType,
                        storeId: that.storeId
                    },
                    app.globalData.userDatatoken.accessToken,
                    '',
                    function success(info) {
                        if (info.code == 0) {
                            if (e == 'refresh') {
                                that.setData({
                                    deviceList: info.data.list
                                });
                            } else {
                                if (info.data != null && info.data.list != null && info.data.list.length <= info.data.total) {
                                    that.setData({
                                        canLoadMore: false
                                    });
                                }
                                let arr = that.deviceList;
                                let arrs = arr.concat(info.data.list);
                                that.setData({
                                    deviceList: arrs
                                });
                            }
                        } else {
                            uni.showModal({
                                content: info.msg,
                                showCancel: false
                            });
                        }
                    },
                    function fail(info) {}
                );
            }
        },

        //门店下拉菜单发生变化
        storeDropdown(event) {
            this.stores.map((it) => {
                if (it.value === event.detail) {
                    this.setData({
                        storeId: it.value
                    });
                }
            });
            this.getDeviceList('refresh');
        },

        //类型下拉菜单发生变化
        typeDropdown(event) {
            let that = this;
            this.deviceTypes.map((it) => {
                if (it.value == event.detail) {
                    if (it.value == -1) {
                        that.setData({
                            deviceType: ''
                        });
                    } else {
                        that.setData({
                            deviceType: it.value
                        });
                    }
                    that.getDeviceList('refresh');
                }
            });
        },

        // 添加
        add() {
            this.setData({
                showAdd: true
            });
        },

        bindDeviceTypeSelect: function (e) {
            this.setData({
                deviceTypeIndex: e.detail.value
            });
        },

        bindStoreSelect: function (e) {
            console.log(e.detail.value);
            if (e.detail.value && e.detail.value != 0) {
                var that = this;
                that.setData({
                    storeIndex: e.detail.value,
                    roomIndex: ''
                });
                that.getRoomListAdmin(that.stores[that.storeIndex].value);
            }
        },

        bindRoomSelect: function (e) {
            this.setData({
                roomIndex: e.detail.value
            });
        },

        changeSwitchStatus: function () {
            this.setData({
                shareDevice: !this.shareDevice // 根据当前状态取反
            });

            console.log(this.shareDevice);
        },

        submitAdd: function () {
            var that = this;
            if (!that.deviceSn) {
                uni.showToast({
                    title: '请输入设备编号',
                    icon: 'error'
                });
                return;
            }
            if (!that.deviceTypeIndex || that.deviceTypeIndex == 0) {
                uni.showToast({
                    title: '请选择设备类型',
                    icon: 'error'
                });
                return;
            }
            if (!that.storeIndex || that.storeIndex == 0) {
                uni.showToast({
                    title: '请选择门店',
                    icon: 'error'
                });
                return;
            }
            var deviceType = that.deviceTypes[that.deviceTypeIndex].value;
            var storeId = that.stores[that.storeIndex].value;
            var roomId = '';
            if (that.roomIndex != 0) {
                roomId = that.roomList[that.roomIndex].value;
            }
            //保存数据
            if (app.globalData.isLogin) {
                http.request(
                    '/member/store/addDevice',
                    '1',
                    'post',
                    {
                        deviceSn: that.deviceSn,
                        shareDevice: that.shareDevice,
                        deviceType: deviceType,
                        storeId: storeId,
                        roomId: roomId
                    },
                    app.globalData.userDatatoken.accessToken,
                    '',
                    function success(info) {
                        console.info('返回111===');
                        if (info.code == 0) {
                            uni.showToast({
                                title: '添加成功',
                                icon: 'success'
                            });
                            that.setData({
                                deviceSn: ''
                            });
                            that.getDeviceList('refresh');
                        } else {
                            uni.showModal({
                                content: '请求服务异常，请稍后重试',
                                showCancel: false
                            });
                        }
                    },
                    function fail(info) {}
                );
            }
        },

        cancelAdd: function () {
            this.setData({
                storeIndex: '',
                deviceTypeIndex: '',
                roomIndex: '',
                shareDevice: false,
                deviceSn: ''
            });
        },

        delDevice: function (e) {
            var that = this;
            var deviceId = e.currentTarget.dataset.id;
            uni.showModal({
                title: '提示',
                content: '确定删除此设备绑定吗？为了避免误操作，仅允许超管操作',
                complete: (res) => {
                    if (res.cancel) {
                    }
                    if (res.confirm) {
                        if (app.globalData.isLogin) {
                            http.request(
                                '/member/store/delDevice/' + deviceId,
                                '1',
                                'post',
                                {},
                                app.globalData.userDatatoken.accessToken,
                                '',
                                function success(info) {
                                    console.info('返回111===');
                                    if (info.code == 0) {
                                        uni.showToast({
                                            title: '删除成功',
                                            icon: 'success'
                                        });
                                        that.getDeviceList('refresh');
                                    } else {
                                        uni.showModal({
                                            content: '请求服务异常，请稍后重试',
                                            showCancel: false
                                        });
                                    }
                                },
                                function fail(info) {}
                            );
                        }
                    }
                }
            });
        }
    }
};
</script>
<style>
@import './deviceList.css';
</style>
